import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { execSync } from "child_process";
import readline from "readline";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建readline接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// 读取.env文件配置
function readEnvConfig() {
  const envPath = path.resolve(__dirname, "../.env");
  const envContent = fs.readFileSync(envPath, "utf8");

  const envVars = {};
  envContent.split("\n").forEach((line) => {
    const trimmedLine = line.trim();
    if (trimmedLine && !trimmedLine.startsWith("#")) {
      const [key, ...valueParts] = trimmedLine.split("=");
      if (key && valueParts.length > 0) {
        const value = valueParts.join("=").trim();
        envVars[key.trim()] = value;
      }
    }
  });

  return envVars;
}

// 询问用户是否压缩
function askUserForCompression() {
  return new Promise((resolve) => {
    rl.question("🤔 是否需要压缩最新版本文件? (y/n/回车默认y): ", (answer) => {
      const input = answer.toLowerCase().trim();
      const shouldCompress =
        input === "y" || input === "yes" || input === "1" || input === "";
      resolve(shouldCompress);
    });
  });
}

// 获取配置路径
function getConfigPaths() {
  const envVars = readEnvConfig();

  // 从.env文件读取配置，如果没有则使用默认值
  const distPath = envVars.VITE_DIST_PATH || "dist/version";
  const zipPath = envVars.VITE_ZIP_PATH || "dist/zip";

  // 解析为绝对路径
  const absoluteDistPath = path.resolve(__dirname, "..", distPath);
  const absoluteZipPath = path.resolve(__dirname, "..", zipPath);

  return { distPath: absoluteDistPath, zipPath: absoluteZipPath };
}

// 检查目录是否存在
function checkDirectories(distPath, zipPath) {
  if (!fs.existsSync(distPath)) {
    console.error(`❌ 目录不存在: ${distPath}`);
    console.error("请先执行构建命令或检查 VITE_DIST_PATH 配置");
    process.exit(1);
  }

  // 确保zip目录存在
  if (!fs.existsSync(zipPath)) {
    fs.mkdirSync(zipPath, { recursive: true });
    console.log(`📁 创建目录: ${zipPath}`);
  }
}

// 生成时间戳 (YYYYMMDDHHMMSS)
function generateTimestamp() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

// 从 package.json 和 .env 文件获取版本信息
function getVersionInfo() {
  const packagePath = path.resolve(__dirname, "../package.json");
  const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
  const envVars = readEnvConfig();
  const timestamp = generateTimestamp();

  return {
    name: envVars.VITE_APP_NAME || packageJson.name,
    version: packageJson.version,
    folderName: `${envVars.VITE_APP_NAME || packageJson.name}-${
      packageJson.version
    }`,
    timestamp: timestamp,
  };
}

// 创建zip文件
function createZipFile(zipFileName, distPath, zipPath) {
  const zipFilePath = path.join(zipPath, zipFileName);

  try {
    // 检查是否已存在同名zip文件，如果存在则删除
    if (fs.existsSync(zipFilePath)) {
      fs.unlinkSync(zipFilePath);
      console.log(`🗑️  删除已存在的 ${zipFileName}`);
    }

    // 使用系统命令创建zip文件，将 distPath 目录下的所有内容打包
    const command = `cd "${distPath}" && zip -r "${zipFilePath}" . -x ".*" -x "__MACOSX/*"`;
    execSync(command, { stdio: "inherit" });

    console.log(`✅ 成功创建压缩文件: ${zipFileName}`);
    console.log(`📁 压缩文件路径: ${zipFilePath}`);

    // 显示压缩文件大小
    const stats = fs.statSync(zipFilePath);
    const fileSizeInMB = (stats.size / (1024 * 1024)).toFixed(2);
    console.log(`📊 压缩文件大小: ${fileSizeInMB} MB`);
  } catch (error) {
    console.error("❌ 创建压缩文件失败:", error.message);
    process.exit(1);
  }
}

// 清理并复制压缩包到 dist 目录
function copyZipToDist(zipFileName, zipPath) {
  // dist 目录的绝对路径
  const distPath = path.resolve(__dirname, "../dist");

  try {
    // 确保 dist 目录存在
    if (!fs.existsSync(distPath)) {
      fs.mkdirSync(distPath, { recursive: true });
      console.log(`📁 创建目录: ${distPath}`);
    }

    // 删除 dist 目录下所有 Template-*.zip 文件
    const files = fs.readdirSync(distPath);
    let deletedCount = 0;
    for (const file of files) {
      if (file.startsWith("Template-") && file.endsWith(".zip")) {
        const filePath = path.join(distPath, file);
        fs.unlinkSync(filePath);
        console.log(`🗑️  删除旧版本压缩包: ${file}`);
        deletedCount++;
      }
    }
    if (deletedCount > 0) {
      console.log(`✅ 已清理 ${deletedCount} 个旧版本压缩包`);
    }

    // 将最新的压缩包复制到 dist 目录
    const sourceZipPath = path.join(zipPath, zipFileName);
    const targetZipPath = path.join(distPath, zipFileName);

    if (fs.existsSync(sourceZipPath)) {
      fs.copyFileSync(sourceZipPath, targetZipPath);
      console.log(`📋 复制压缩包到 dist 目录: ${zipFileName}`);
    } else {
      console.error(`❌ 源文件不存在: ${sourceZipPath}`);
    }
  } catch (error) {
    console.error("❌ 复制压缩包失败:", error.message);
  }
}

// 主函数
async function main() {
  try {
    // 获取命令行参数
    const args = process.argv.slice(2);
    const shouldAsk = args[0] === "yes";

    // 获取配置路径
    const { distPath, zipPath } = getConfigPaths();
    console.log(`📂 读取目录: ${distPath}`);
    console.log(`📦 压缩目录: ${zipPath}`);

    // 检查目录
    checkDirectories(distPath, zipPath);

    if (shouldAsk) {
      console.log("🔍 正在获取版本信息...");

      const versionInfo = getVersionInfo();
      console.log(`📦 版本信息: ${versionInfo.folderName}`);
      console.log(`📂 压缩源目录: ${distPath}`);

      const shouldCompress = await askUserForCompression();

      if (shouldCompress) {
        // 直接在 version 目录下压缩所有内容，文件名加上时间戳
        const zipFileName = `${versionInfo.folderName}-${versionInfo.timestamp}.zip`;
        createZipFile(zipFileName, distPath, zipPath);
        // 复制到 dist 目录并清理旧版本
        copyZipToDist(zipFileName, zipPath);
        console.log("🎉 压缩完成!");
      } else {
        console.log("⏭️  跳过压缩操作");
      }
    } else {
      // 直接执行压缩（用于 npm run dist）
      console.log("🔍 正在获取版本信息...");

      const versionInfo = getVersionInfo();
      console.log(`📦 版本信息: ${versionInfo.folderName}`);
      console.log(`📂 压缩源目录: ${distPath}`);

      // 直接在 version 目录下压缩所有内容，文件名加上时间戳
      const zipFileName = `${versionInfo.folderName}-${versionInfo.timestamp}.zip`;
      createZipFile(zipFileName, distPath, zipPath);
      // 复制到 dist 目录并清理旧版本
      copyZipToDist(zipFileName, zipPath);

      console.log("🎉 压缩完成!");
    }
  } catch (error) {
    console.error("❌ 脚本执行失败:", error.message);
    process.exit(1);
  } finally {
    // 关闭readline接口
    rl.close();
  }
}

// 执行主函数
main();
